// pages/deviceinfo/deviceinfo.js
var util = require('../../utils/util.js'); 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    admininfo: null,

    deviceid: null,
    devicename: null,
    deviceprovider: null,
    devicetype: null,
    amount: null,
    deviceowner: null,
    deviceownerid: null,
    devicedetail: null,
    deviceimage: null,
    devicerentdate: null,
    deviceNum:null,

    obj:null,

    hostername: null,
    hosterid: null,

    takenhour: null,

    numarray: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
    numindex: 0,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData
      ({
        deviceid: options.deviceid,
        hosterid: options.hosterid
      })

    //1.获取token
    wx.request({
      url: "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential",
      data: {
        appid: getApp().globalData.appID,
        secret: getApp().globalData.appSecret
      },
      success: function (res) {
        console.log('access_token:', res.data.access_token)
        getApp().globalData.access_token = res.data.access_token;
      }
    })

    /* 初始化数据库 */
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('Hoster').where
      ({
        _openid: _.eq(this.data.hosterid)
      })
      .get
      ({
        success: res => {
          this.setData(
            {
              hostername: res.data[0].names,
            }
          )
          console.log('用户名查询成功:', res.data)

        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    /* 初始化数据库 */
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('Device').where
      ({
        _id: _.eq(this.data.deviceid)
      })
      .get
      ({
        success: res => {

          var arr = res.data[0].owner
          var obj = {};
          for (var i = 0; i < arr.length; i++) {
            if (!obj[arr[i]]) {
              obj[arr[i]] = 1;
            }
            else {
              obj[arr[i]]++
            }
          }
          // console.log('obj:', obj)

          var objValue = 0;
          var objStr = arr[0];
          var objRes = ""
          for (var i in obj) {
        
              objValue = obj[i];
              objStr = i;
              objRes = objRes + objStr + "(" + objValue + ")"
        
          }

          console.log('objRes:', objRes);


          this.setData(
            {
              devicename: res.data[0].name,
              deviceprovider: res.data[0].provider,
              amount: res.data[0].amount,
              deviceowner: res.data[0].owner,
              deviceownerid: res.data[0].ownerid,
              devicedetail: res.data[0].adding,
              deviceimage: res.data[0].image,
              devicetype: res.data[0].dtype,
              // collectionStatus: res.data[0].collectionStatus,
              // collectionNum: res.data[0].collectionNum,
              // bookrentrecord: res.data[0].rentrecord,
              devicerentdate: res.data[0].rentdate,
              deviceNum:res.data[0].deviceNum,
              obj: objRes,
            }
          )
          console.log('数据库查询成功:', res.data)

        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },


  //数量选择
  numPickerChange: function (e) {
    console.log('picker 值为:', e.detail.value)
    this.setData({
      numindex: e.detail.value
    })
  },


  //借阅按钮
  rentDevice: function (event) {

    var rentnum = this.data.numarray[this.data.numindex]
    console.log('rentnum', rentnum)

    var timestamp = Date.parse(new Date());
    var devicenum = parseInt(this.data.amount)
    timestamp = timestamp / 1000;
    console.log("当前时间戳为：" + timestamp);

    this.setData
      ({
        takenhour: timestamp
      })
    if (rentnum <= devicenum) {
      if (this.data.hostername != '无') {
        const db = wx.cloud.database()
        const _ = db.command
        db.collection('Devicerentlist').add
          ({
            data: {
              deviceid: this.data.deviceid,
              devicename: this.data.devicename,
              devicetype: this.data.devicetype,
              rentnum: rentnum,
              rentdate: this.data.takenhour,
              asker: this.data.hostername,
              askerid: this.data.hosterid
            }
          })
        db.collection('Admins')
          .get
          ({
            success: res => {
              this.setData(
                {
                  admininfo: res.data
                }
              )
              wx.showToast({
                title: '申请已提交',
                icon: 'error',
                duration: 2000          //提示的延迟时间
              })

              var length = this.data.admininfo.length
              for (var i = 0; i < length; i++) {
                var adminid = this.data.admininfo[i].hosterid
                //2.向wanterid发送图书可借通知

                //准备模版数据
                console.log('getApp()_token:', getApp().globalData.access_token)
                let _access_token = getApp().globalData.access_token;
                let url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + _access_token;
                let temp = new Date(1000 * this.data.takenhour)
                let sendtime = util.formatTime(temp)
                let _jsonData = {
                  access_token: _access_token,
                  // touser: 'ow6NN5VmfGWIwdAbO4kiyqMX8Y28',
                  touser: adminid,
                  template_id: getApp().globalData.rentask,
                  form_id: event.detail.formId,
                  page: "pages/rentdevicelist/rentdevicelist",
                  data: {
                    "keyword1": { "value": this.data.hostername, "color": "#173177" },
                    "keyword2": { "value": this.data.devicename, "color": "#173177" },
                    "keyword3": { "value": sendtime, "color": "#173177" },
                    "keyword4": { "value": this.data.hostername + "想借用" + this.data.devicename + ",请前往批准", "color": "#173177" }
                  },
                  //需要放大的关键字
                  // emphasis_keyword: 'keyword1.DATA'
                }
                //发送模版消息
                wx.request({
                  url: url,
                  data: _jsonData,
                  method: 'POST',
                  success: function (res) {
                    console.log(res)
                  },
                  fail: function (err) {
                    console.log('request fail ', err);
                  },
                  complete: function (res) {
                    console.log("request completed!");
                  }

                })

                console.log('完成')
              }

            },
            fail: err => {
              wx.showToast({
                icon: 'none',
                title: '查询记录失败'
              })
              console.error('数据库查询失败', err)
            }
          })


      } else {
        wx.showToast({
          title: '你必须先实名注册',
          icon: 'error',
          duration: 2000          //提示的延迟时间
        })
      }
    } else {

      wx.showToast({
        title: '库存不足',
        icon: 'error',
        duration: 2000          //提示的延迟时间
      })

    }


    // if (this.data.hostername != '无') {
    //   var aflag = 0
    //   var numflag = 0
    //   var deviceownertem = this.data.deviceowner
    //   var deviceowneridtem = this.data.deviceownerid
    //   var length = deviceowneridtem.length
    //   var devicenum = this.data.amount
    //   var devicerentdatetem = this.data.devicerentdate


    //   if (rentnum <= devicenum) {

    //     devicenum = devicenum - rentnum

    //     for (var j = 0; j < length; j++) {
    //       if (deviceowneridtem[j] == '空' && aflag == 0) {     
    //         console.log('devicenum',devicenum)
    //         deviceowneridtem[j] = this.data.hosterid
    //         deviceownertem[j] = this.data.hostername
    //         devicerentdatetem[j] = this.data.takenhour
    //         numflag = numflag + 1
    //         console.log('numflag', numflag)

    //         if (numflag == rentnum) {
    //           this.setData
    //             ({
    //               devicerentdate: devicerentdatetem,
    //               deviceowner: deviceownertem,
    //               deviceownerid: deviceowneridtem,
    //               amount: devicenum
    //             })
    //           break
    //         }
    //       }
    //     }
    //     wx.cloud.callFunction
    //       ({
    //         // 云函数名称
    //         name: 'rentdevice',
    //         // 传给云函数的参数
    //         data:
    //         {
    //           deviceid: this.data.deviceid,
    //           deviceowner: this.data.deviceowner,
    //           deviceownerid: this.data.deviceownerid,
    //           hostername: this.data.hostername,
    //           hosterid: this.data.hosterid,
    //           devicenum: this.data.amount,
    //           devicerentdate: this.data.devicerentdate,
    //         },

    //         success: function (res) {
    //           console.log(res)
    //         },

    //         fail: console.error
    //       })

    //     wx.showToast({
    //       title: '借用成功',
    //       icon: 'error',
    //       duration: 2000          //提示的延迟时间
    //     })
    //     console.log('wxfu2')

    //   } else {
    //     wx.showToast({
    //       title: '没有足够的库存',
    //       icon: 'error',
    //       duration: 2000          //提示的延迟时间
    //     })

    //   }




    // } else {
    //   wx.showToast({
    //     title: '你必须先实名注册',
    //     icon: 'error',
    //     duration: 2000          //提示的延迟时间
    //   })
    //  }



  },

  formSubmit: function (e) {

    console.log('form发生了submit事件，fromId为：', e.detail.formId)
    this.setData
      ({
        formid: e.detail.formId
      })
  },

  //还书按钮
  returndevice: function () {

    var deviceowner = this.data.deviceowner
    if (this.data.hostername != '无') {
      var deviceownertem = this.data.deviceowner
      var deviceowneridtem = this.data.deviceownerid
      var length = deviceowneridtem.length
      var devicenumtem = this.data.amount
      var returnnum = 0

      for (var i = 0; i < length; i++) {
        if (deviceowneridtem[i] == this.data.hosterid) {
          deviceowneridtem[i] = '空'
          deviceownertem[i] = '无人'
          returnnum = returnnum + 1
          this.setData
            ({
              deviceownerid: deviceowneridtem,
              deviceowner: deviceownertem
            })
        }
      }
      devicenumtem = devicenumtem + returnnum
      this.setData
        ({
          amount: devicenumtem
        })

      wx.cloud.callFunction({
        // 云函数名称
        name: 'returndevice',
        // 传给云函数的参数
        data: {
          deviceid: this.data.deviceid,
          deviceownerid: this.data.deviceownerid,
          deviceowner: this.data.deviceowner,
          devicenum: devicenumtem,
        },
        success: function (res) {
          console.log(res)
        },
        fail: console.error
      })


      wx.showToast({
        title: '还书成功！',
        icon: 'error',
        duration: 2000          //提示的延迟时间
      })

    } else {
      wx.showToast({
        title: '你必须先实名注册',
        icon: 'error',
        duration: 2000          //提示的延迟时间
      })
    }


  }

})